<?php

namespace app\admin\controller\system;

use albert\services\CacheService;
use albert\services\FormBuilder;
use albert\services\JsonService;
use albert\services\UtilService;
use app\admin\controller\AuthController;
use app\model\system\SystemGroup;
use app\model\system\SystemGroupData;
use FormBuilder\exception\FormBuilderException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 组合数据值控制器
 * Class GroupDataController
 * @package app\admin\controller\system
 */
class GroupDataController extends AuthController
{
    /**
     * 组数据列表展示页
     * Author: Albert3306
     * Date: 2021/7/7
     * @param int $gid
     * @return string
     * @throws DbException
     */
    public function index(int $gid = 0): string
    {
        $params = UtilService::param([
            ['gid', 0],
            ['status', ''],
        ], $this->request);
        if ($gid) $params['gid'] = $gid;
        $this->assign(SystemGroupData::getList($params));
        return $this->fetch('system/group_data/index', [
            'gid' => $gid,
            'params' => $params,
            'fields' => SystemGroup::getField($gid)
        ]);
    }

    /**
     * 添加组数据
     * Author: Albert3306
     * Date: 2021/7/7
     * @param $gid
     * @return string
     * @throws FormBuilderException
     */
    public function create($gid): string
    {
        $f = [];
        $fields = SystemGroup::getField($gid);
        foreach ($fields as $value) {
            $info = SystemGroup::dealField($value);
            switch ($value['type']) {
                case 'textarea':
                    $f[] = FormBuilder::input($value['title'], $value['name'])->type('textarea')->placeholder($value['param']);
                    break;
                case 'radio':
                    $f[] = FormBuilder::radio($value['title'], $value['name'], $info[0]['value'] ?? '')->options($info);
                    break;
                case 'checkbox':
                    $f[] = FormBuilder::checkbox($value['title'], $value['name'], $info[0] ?? '')->options($info);
                    break;
                case 'select':
                    $f[] = FormBuilder::select($value['title'], $value['name'], $info[0] ?? '')->options($info)->multiple(false);
                    break;
                case 'upload':
                    $f[] = FormBuilder::frameImageOne($value['title'], $value['name'], '/admin/widget/images?fodder=' . $value['title'])->icon('image')->width('100%')->height('500px');
                    break;
                case 'uploads':
                    $f[] = FormBuilder::frameImages($value['title'], $value['name'], '/admin/widget/images?fodder=' . $value['title'])->maxLength(5)->icon('images')->width('100%')->height('500px')->spin(0);
                    break;
                case 'number':
                    $f[] = FormBuilder::number($value['title'], $value['name'])->precision('int');
                    break;
                default:
                    $f[] = FormBuilder::input($value['title'], $value['name']);
                    break;

            }
        }
        $f[] = FormBuilder::number('sort', '排序', 1);
        $f[] = FormBuilder::radio('status', '状态', 1)->options([['value' => 1, 'label' => '显示'], ['value' => 2, 'label' => '隐藏']]);
        $form = FormBuilder::make_post_form('添加数据', $f, '/admin/system/group/data_save/' . $gid);
        return $this->fetch('public/form-builder', compact('form'));
    }

    /**
     * 添加保存
     * Author: Albert3306
     * Date: 2021/7/7
     * @param $gid
     * @return string
     */
    public function save($gid): string
    {
        $fields = SystemGroup::getField($gid);
        $params = request()->post();
        $value = [];
        foreach ($params as $key => $param) {
            foreach ($fields as $field) {
                if ($key == $field['title']) {
                    if ($param == '')
                        return JsonService::fail($field['name'] . '不能为空！');
                    else {
                        $value[$key]['type'] = $field['type'];
                        $value[$key]['value'] = $param;
                    }
                }
            }
        }

        $data = ['gid' => $gid, 'add_time' => time(), 'value' => htmlspecialchars_decode(json_encode($value)), 'sort' => $params['sort'], 'status' => $params['status']];
        SystemGroupData::create($data);
        CacheService::clear();
        return JsonService::successful('添加数据成功！');
    }

    /**
     * 编辑
     * Author: Albert3306
     * Date: 2021/7/7
     * @param $gid
     * @param $id
     * @return string
     * @throws DbException
     * @throws FormBuilderException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function edit($gid, $id): string
    {
        $f = [];
        $GroupData = SystemGroupData::get($id);
        $GroupDataValue = json_decode($GroupData['value'], true);
        $fields = SystemGroup::getField($gid);
        if (!isset($fields)) return $this->failed('数据解析失败！');
        foreach ($fields as $value) {
            $info = SystemGroup::dealField($value);
            $fValue = $GroupDataValue[$value['title']]['value'] ?? '';
            switch ($value['type']) {
                case 'textarea':
                    $f[] = FormBuilder::input($value['title'], $value['name'], $fValue)->type('textarea');
                    break;
                case 'radio':
                    $f[] = FormBuilder::radio($value['title'], $value['name'], $fValue)->options($info);
                    break;
                case 'checkbox':
                    $f[] = FormBuilder::checkbox($value['title'], $value['name'], $fValue)->options($info);
                    break;
                case 'upload':
                    if (!empty($fValue)) {
                        $image = is_string($fValue) ? $fValue : $fValue[0];
                    } else {
                        $image = '';
                    }
                    $f[] = FormBuilder::frameImageOne($value['title'], $value['name'], '/admin/widget/images?fodder=' . $value['title'], $image)->icon('image')->width('100%')->height('500px');
                    break;
                case 'uploads':
                    $images = !empty($fValue) ? $fValue : [];
                    $f[] = FormBuilder::frameImages($value['title'], $value['name'], '/admin/widget/images?fodder=' . $value['title'], $images)->maxLength(5)->icon('images')->width('100%')->height('500px')->spin(0);
                    break;
                case 'select':
                    $f[] = FormBuilder::select($value['title'], $value['name'], $fValue)->setOptions($info);
                    break;
                case 'number':
                    $f[] = FormBuilder::number($value["title"], $value["name"])->precision('int');
                    break;
                default:
                    $f[] = FormBuilder::input($value['title'], $value['name'], $fValue);
                    break;

            }
        }
        $f[] = FormBuilder::number('sort', '排序', $GroupData["sort"]);
        $f[] = FormBuilder::radio('status', '状态', $GroupData["status"])->options([['value' => 1, 'label' => '显示'], ['value' => 2, 'label' => '隐藏']]);
        $form = FormBuilder::make_post_form('添加用户通知', $f, '/admin/system/group/data_update/' . $id);
        return $this->fetch('public/form-builder', compact('form'));
    }

    /**
     * 编辑保存
     * Author: Albert3306
     * Date: 2021/7/7
     * @param $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function update($id): string
    {
        $GroupData = SystemGroupData::get($id);
        $fields = SystemGroup::getField($GroupData['gid']);
        $params = request()->post();
        $value = [];
        foreach ($params as $key => $param) {
            foreach ($fields as $field) {
                if ($key == $field['title']) {
                    if (trim($param) == '')
                        return JsonService::fail($field['name'] . '不能为空！');
                    else {
                        $value[$key]['type'] = $field['type'];
                        $value[$key]['value'] = $param;
                    }
                }
            }
        }
        $data = ['value' => htmlspecialchars_decode(json_encode($value)), 'sort' => $params['sort'], 'status' => $params['status']];
        SystemGroupData::edit($data, $id);
        CacheService::clear();
        return JsonService::successful('修改成功!');
    }

    /**
     * 删除
     * Author: Albert3306
     * Date: 2021/7/7
     * @param $id
     * @return string
     */
    public function delete($id): string
    {
        if (!SystemGroupData::del($id)) return JsonService::fail(SystemGroupData::getErrorInfo('删除失败，请稍候再试！'));
        CacheService::clear();
        return JsonService::successful('删除成功！');
    }
}